package com.ysucode.controller.user;

import com.ysucode.annotation.MyLogger;
import com.ysucode.constant.CheckCode;
import com.ysucode.constant.Register;
import com.ysucode.domain.User;
import com.ysucode.entity.Result;
import com.ysucode.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@Controller
public class UserController {
    @Autowired
    private PasswordEncoder bcrypt;
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String index() {
        return "index";
    }

    //用户注册
    @MyLogger("用户注册")
    @RequestMapping("/registerServlet")
    @ResponseBody
    public Result register(String username,
                           String email,
                           String password,
                           String checkcode,
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
        //从session获取生成的验证码
        HttpSession session = request.getSession();
        String checkcodegen = (String) session.getAttribute("checkcodegen");
        //查询用户名
        User user = userService.getByUsername(username);
        //不可以注册
        if (!checkcodegen.equalsIgnoreCase(checkcode)) { //注册验证码错误
            log.debug(CheckCode.ERROR);
            return new Result(false, CheckCode.ERROR);
        } else if (user != null) { //重名时
            log.debug(Register.REG_NAME);
            return new Result(false, Register.REG_NAME);
        }
        //可以注册
        int affectedRows = userService.addUser(new User(username, bcrypt.encode(password), email, User.COMMON));
        if (affectedRows == 0) { //注册失败
            log.debug(Register.REG_ERROR);
            return new Result(false, Register.REG_ERROR);
        }
        //注册成功
        log.debug(Register.REG_SUCCESS);
        return new Result(true, Register.REG_SUCCESS);
    }


}
